/**
 * Copyright © 2022 易久批信息技术有限公司. All rights reserved.
 */
package com.dysm.pc;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *
 * @author xiay
 * @since 2022/4/6 8:00 下午
 */
public class WaitConsumer implements Runnable {

    private CopyOnWriteArrayList<Integer> list;

    public WaitConsumer(CopyOnWriteArrayList<Integer> list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                try {
                    double v = new Random().nextDouble();
                    Thread.sleep((long) ((long) 1000 * v));
                    if (list.size() == 0) {
                        System.out.println("没有可以消费的了，先休息一下");
                        list.wait();
                    }
                    consumer(list.remove(0));
                    list.notify();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void consumer(Integer integer) {
        System.out.println(Thread.currentThread().getName() + "，消费者消费：" + integer);
    }
}
